package util;

import lombok.Getter;
import lombok.Setter;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Objects;


//@SuppressWarnings("unused")
public class ImageView extends JPanel {
    @Getter
    @Setter
    private Image image;
    private int rows;
    private int cols;
    @Getter
    @Setter
    private int[][] data;

    public void setDateElement(int x, int y, int value) {
        data[x][y] = value;
    }

    public int getDataElement(int x, int y) {
        return data[x][y];
    }

    public void loadOrUpdateImageResources(String dirPath, int rows, int cols) {
        File dir = new File(dirPath);
        File[] files = dir.listFiles();

        boolean useDefaultImage = false;

        if (!dir.exists() || !dir.isDirectory() || Objects.requireNonNull(files).length == 0) {
            useDefaultImage = true;
        } else {
            String type = ImageHandle.getImageType(files, "whole");
            File wholeImage = null;
            if (type != null) {
                wholeImage = new File(dir, "whole." + type);
            } else {
                useDefaultImage = true;
            }

            if (!useDefaultImage  && !wholeImage.exists()) {
                useDefaultImage = true;
            }
        }

        if (useDefaultImage) {
            String defaultRunPlace = JsonRW.getStr(JsonRW.configFile, "runPath") + "/0";
            ImageHandle.splitImage(JsonRW.getStr(JsonRW.configFile, "defaultImage"), defaultRunPlace, rows, cols, JsonRW.getInt(JsonRW.configFile, "widthWhole"), JsonRW.getInt(JsonRW.configFile, "heightWhole"));
            dir = new File(defaultRunPlace);
        }

        String type = ImageHandle.getImageType(Objects.requireNonNull(dir.listFiles()), "whole");

        File wholeImage;
        if (type != null) {
            wholeImage = new File(dir, "whole." + type);
        } else {
            throw new RuntimeException("未检测到whole文件！");
        }

        if (!wholeImage.exists()) {
            throw new RuntimeException("未检测到whole文件！");
        }

        this.image = new ImageIcon(wholeImage.getPath()).getImage();
        this.rows = rows;
        this.cols = cols;

        if (data == null || data.length != rows || data[0].length != cols) {
            data = new int[rows][cols];
        }

        setPreferredSize(new Dimension(image.getWidth(null), image.getHeight(null)));
    }


    public ImageView(String filePath, int rows, int cols) {
        loadOrUpdateImageResources(filePath, rows, cols);
        enableInputMethods(false);

    }

    private Image getSubimage(Image image, int x, int y, int width, int height) {
        if (image instanceof BufferedImage) {
            return ((BufferedImage) image).getSubimage(x, y, width, height);
        } else {
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics g = bufferedImage.getGraphics();
            g.drawImage(image, 0, 0, width, height, x, y, x + width, y + height, null);
            g.dispose();
            return bufferedImage;
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        if (image == null) {
            return;
        }

        if (rows == 1 && cols == 1) {
            loadOrUpdateImageResources(g, image, 0, 0, getWidth(), getHeight());
        } else if (rows > 1 && cols > 1) {
            drawCroppedImages(g);
        } else {
            throw new RuntimeException("非法的行数或列数！");
        }
    }

    public void loadOrUpdateImageResources(Graphics g, Image image, int x, int y, int width, int height) {
        g.drawImage(image, x, y, width, height, null);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setStroke(new BasicStroke(JsonRW.getInt(JsonRW.configFile, "wholeImageBorderSize")));   // 设置边框粗细
        g2d.setColor(Color.GRAY); // 设置边框颜色
        g2d.drawRect(x, y, width, height);
    }

    public void drawCroppedImages(Graphics g) {
        if (data == null) {
            return;
        }

        if (data.length != rows || data[0].length != cols) {
            throw new RuntimeException("数据行列数与图片切割行列数不匹配！");
        }

        int smallImageWidth = image.getWidth(null) / cols;
        int smallImageHeight = image.getHeight(null) / rows;

        // 转换为 Graphics2D 以设置笔画属性
        Graphics2D g2d = (Graphics2D) g;
        g2d.setStroke(new BasicStroke(JsonRW.getInt(JsonRW.configFile, "subImageBorderSize"))); // 设置边框粗细
        g2d.setColor(Color.GRAY); // 设置边框颜色

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int x = j * smallImageWidth;
                int y = i * smallImageHeight;

                int dataIndex = data[i][j];
                if (dataIndex > 0) {
                    int srcRow = (dataIndex - 1) / cols;
                    int srcCol = (dataIndex - 1) % cols;
                    int srcX = srcCol * smallImageWidth;
                    int srcY = srcRow * smallImageHeight;
                    Image subImage = getSubimage(image, srcX, srcY, smallImageWidth, smallImageHeight);
                    loadOrUpdateImageResources(g, subImage, x, y, smallImageWidth, smallImageHeight);

                    // 绘制边框
                    g2d.drawRect(x, y, smallImageWidth, smallImageHeight);
                }
            }
        }
    }
}